package com.xiaobao.coalproperty.module.user.view;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.xiaobao.coalproperty.R;
import com.xiaobao.coalproperty.module.home.model.entity.BlankEntity;
import com.xiaobao.coalproperty.module.user.model.entity.UploadPicEntity;
import com.xiaobao.coalproperty.other.adapter.TopicAdapter;
import com.xiaobao.coalproperty.other.base.BaseActivity;
import com.xiaobao.coalproperty.other.constant.UrlConstant;
import com.xiaobao.coalproperty.other.util.HttpHelperUtils;
import com.xiaobao.coalproperty.other.util.UserHelperUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;

import butterknife.BindView;
import okhttp3.Call;

public class UserAuthActivity extends BaseActivity {


    @BindView(R.id.recycler)
    XRecyclerView mXRecyclerView;

    private ImageView ivAuthing, ivAuthFial, ivFront, ivBack, ivAdd;
    private EditText edtName, edtNum;
    private LinearLayout llAuthData;

    private View headView;
    private String AUTH_TYPE;
    private File frontFile, backFile, addFile;
    private String frontUrl, backUrl, addUrl;

    @Override
    protected int getContentView() {
        return R.layout.recycler;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setLeftClickFinish();
        setTitle("实名认证");

        headView = LayoutInflater.from(this).inflate(R.layout.activity_user_auth, null, false);
        ivAuthing = headView.findViewById(R.id.auth_authing);
        ivAuthFial = headView.findViewById(R.id.auth_fail);
        llAuthData = headView.findViewById(R.id.auth_data);
        edtName = headView.findViewById(R.id.auth_name);
        edtNum = headView.findViewById(R.id.auth_num);
        ivFront = headView.findViewById(R.id.auth_front);
        ivBack = headView.findViewById(R.id.auth_back);
        ivAdd = headView.findViewById(R.id.auth_add);


        ivFront.setOnClickListener(mOnClickListener);
        ivBack.setOnClickListener(mOnClickListener);
        ivAdd.setOnClickListener(mOnClickListener);

        mXRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mXRecyclerView.addHeaderView(headView);
        mXRecyclerView.setLoadingListener(mLoadingListener);
        mXRecyclerView.setAdapter(new TopicAdapter(this));

        AUTH_TYPE = getIntent().getStringExtra(getIntent().getAction());

        if (AUTH_TYPE.equals("1")) {
            llAuthData.setVisibility(View.GONE);
            ivAuthing.setVisibility(View.VISIBLE);
        } else if (AUTH_TYPE.equals("2")) {
            llAuthData.setVisibility(View.GONE);
            ivAuthFial.setVisibility(View.VISIBLE);
        }

    }

    private XRecyclerView.LoadingListener mLoadingListener = new XRecyclerView.LoadingListener() {
        @Override
        public void onRefresh() {
            mXRecyclerView.refreshComplete();
        }

        @Override
        public void onLoadMore() {
            mXRecyclerView.loadMoreComplete();
        }
    };

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.auth_front:
                    startImageActivity(1);
                    break;
                case R.id.auth_back:
                    startImageActivity(2);
                    break;
                case R.id.auth_add:
                    startImageActivity(3);
                    break;
            }
        }
    };

    private void startImageActivity(int index) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .compress(true)
                .forResult(index);
    }

    public void onUserAuthClick(View view) {
        if(TextUtils.isEmpty(frontUrl)){
            showToast("请上传身份证正面照片");
            return;
        }
        if(TextUtils.isEmpty(backUrl)){
            showToast("请上传身份证背面照片");
            return;
        }
        if(TextUtils.isEmpty(addUrl)){
            showToast("请上传手持身份证照片");
            return;
        }
        submit();
    }

    // 1.media.getPath(); 为原图path 2.media.getCutPath();为裁剪后path 3.media.getCompressPath();为压缩后path
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:
                    frontFile = new File(PictureSelector.obtainMultipleResult(data).get(0).getPath());
                    ivFront.setImageURI(Uri.fromFile(frontFile));
                    uploadHeadImage(frontFile, 1);
                    break;
                case 2:
                    backFile = new File(PictureSelector.obtainMultipleResult(data).get(0).getPath());
                    ivBack.setImageURI(Uri.fromFile(backFile));
                    uploadHeadImage(backFile, 2);
                    break;
                case 3:
                    addFile = new File(PictureSelector.obtainMultipleResult(data).get(0).getPath());
                    ivAdd.setImageURI(Uri.fromFile(addFile));
                    uploadHeadImage(addFile, 3);
                    break;
            }
        }
    }

    private void submit(){
        OkHttpUtils.post().url(UrlConstant.URL_CERTIFICATION_SUBMIT)
                .params(HttpHelperUtils.getInstance().certificationSubmit(edtName.getText().toString(),edtNum.getText().toString(),frontUrl,backUrl,addUrl))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    BlankEntity entity = new Gson().fromJson(response,BlankEntity.class);
                    showToast(entity.getMsg());
                    if(entity.getCode()==0){
                        finish();
                    }
                }catch (Exception e){}
            }
        });
    }

    private void uploadHeadImage(File file, final int type) {
        String filename = UserHelperUtils.getInstance().getHashId() + "" + System.currentTimeMillis() + "" + file.getName();
        OkHttpUtils.post().url(UrlConstant.URL_UPLOAD_PICTURE)
                .addFile("uploadname", filename, file)
                .params(HttpHelperUtils.getInstance().uploadPictureParams())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    UploadPicEntity entity = new Gson().fromJson(response, UploadPicEntity.class);
                    if (entity.getCode() == 0) {
                        switch (type) {
                            case 1:
                                frontUrl = entity.getData();
                                break;
                            case 2:
                                backUrl = entity.getData();
                                break;
                            case 3:
                                addUrl = entity.getData();
                                break;
                        }
                    }
                } catch (Exception e) {
                }
            }
        });
    }
}
